<?php
/**
 * 前台评论控制器
 */
class CommentAction extends Action {
    private $safetyTime=5;//5分钟
	public function _initialize()
	{
		$this->currentModel = D(MODULE_NAME);
	}
	
    /**
    * 发布评论
    * @access public
    */
    public function add()
    {
    	if($this->isPost())
    	{
            if($this->safety($this->_post('username'),$this->_post('value_id')))
            {
                if($_SESSION['verify']!= md5($_POST['verify']))
                {
                    $this->ajaxReturn(0,'验证码错误！',0); 
                }
                $data=$this->currentModel->create();
                if($data===FALSE)
                {
                    $this->ajaxReturn(0,$this->currentModel->getError(),0);
                }
                $data['content']=htmlspecialchars($data['content']);
                if($this->currentModel->add($data)!==FALSE)
                {
                    $data['faceImg']=show_gravatar($data['email'],$data['username']);
                    $data['add_time']=date('Y-m-d',$data['add_time']);
                    $this->ajaxReturn($data,'评论成功',1);
                }                
            }else
                {
                   $this->ajaxReturn(0,'你果然活跃，请休息一下再发表',0); 
                }
    	}else
    		{
                $this->ajaxReturn(0,'非法操作',0);
    		}
    }

    private function safety($userName,$id)
    {
        $ok=false;
        $where['username']=$userName;
        $where['value_id']=$id;
        $where['ip_address']=get_client_ip();
        $where['parent_id']=0;
        $data=$this->currentModel->field('add_time')->where($where)->order('id DESC')->find();
        if(empty($data))
        {
            $ok=true;
        }else
            {
                $temp=time()-$data['add_time'];
                $sec = round($temp/60); 
                $min = str_pad($sec%60, 2, 0, STR_PAD_LEFT);           
                if($min>$this->safetyTime)
                {
                    $ok=true;
                }
            }
        return $ok;
    }

  /*验证码*/
  public function verify()
  {
    $type =isset($_GET['type'])?$_GET['type']:'gif';
    import("@.ORG.Image");
    Image::buildImageVerify(4,1,$type);
  } 

}